
// IS_REACTIVE 相应式变量标识，这些标识不会声明到响应式变量对象中，当通过代理访问的时候会给出不同的相应
import { effect,cleanup } from './effect.js';
let ReactiveFlags = {
    IS_REACTIVE:'__v_isReactive'
  };
  const isProxy = (obj)=>{
    
    return obj[ReactiveFlags.IS_REACTIVE];
  }
function createWatchEffect(getter,options){
  
    let effetcFn = null;
      effetcFn =  effect(getter, {
        user: false, 
        immediate:options?.immediate ?? null,
        fn:options?.fn ?? null, 
        ...options
      });
      // effect是watchEffect的唯一标识
      if(!options.effect){ 
      effetcFn(); 
      } 
      effetcFn.stop = ()=>cleanup(effetcFn);
      return effetcFn; 
  }

// 实现watchEffect
// 实现stop,onInvalidate
 export function watchEffect(fn,options){
 
     const effetcFn = createWatchEffect(fn,{
          ...options,
          lazy:true,
          effect:true,
      }); 
      return effetcFn.stop;
 }


  // 实现watch
  export function watch(getter,fn,options = {}){
    let {deep=false} = options; 
    options.fn = fn;
    let getterfn = getter; 
    if(typeof getter == 'string'){
        console.log('Arguments 1 must is a Function or Object!')
            return 
        } 
          if(isProxy(getter)){ 
            for(let key in getter){ 
              if(typeof getter[key] == 'object'){
                // deep成立时需要深度递归监听
                if(deep){
                  watch(getter[key],fn,options)  
                } 
              }else{
                  watch(()=>getter[key],fn,options)  
              }  
            }
            createWatchEffect(()=>getter,options)
            return getter;
        } 
        if(getter.__is_ref){  
          getterfn = ()=>getter.value
       } 
       createWatchEffect(getterfn,options) 
      
  }
  